<!--
 * @Description:封装缓动基本函数
 * @Author: Sun
 * @Date: 2019-07-01 20:05:50
 * @LastEditors: Sun
 * @LastEditTime: 2019-07-21 17:21:53
 -->
<!DOCTYPE html>
<html lang="en">

<head>
	<meta charset="UTF-8">
	<meta name="viewport" content="width=device-width, initial-scale=1.0">
	<meta http-equiv="X-UA-Compatible" content="ie=edge">
	<title>封装缓动基本函数</title>
	<style>
		* {
			margin: 0;
			padding: 0
		}
		div {
			width: 100px;
			height: 100px;
			background-color: pink;
			position: absolute;
			left: 0px;
		}
	</style>
</head>

<body>
	<button id="btn200"> 200</button>
	<button id="btn400">400</button>
	<div id="box">点击按钮</div>
	<script>
		function $(id) {
			return document.getElementById(id);
		}
		window.onload = function () {
			var btn200 = $("btn200")
			var btn400 = $("btn400")
			var timer = null
			var box = $("box")
			btn200.onclick = function () {
				animate(box, 200)
			}
			btn400.onclick = function () {
				animate(box, 400)
			}
			//封装函数 1 动谁 2 动多少
			function animate(obj, target) {
				clearInterval(obj.timer)
				obj.timer = setInterval(() => {
					//计算步长  动画原理 盒子本身位置+步长
					var step = (target - obj.offsetLeft) / 10; //步长
					step = step > 0 ? Math.ceil(step) : Math.floor(step) //取整步长
					obj.style.left = obj.offsetLeft + step + "px"
					if (obj.offsetLeft == target) {
						clearInterval(timer)
					}
				}, 30)
			}

		}
	</script>

</body>

</html>